package cn.xxi.ai.workflow.core.node;

import cn.xxi.ai.workflow.state.State;
import lombok.extern.slf4j.Slf4j;
import org.bsc.langgraph4j.action.NodeAction;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;

@Slf4j
public abstract class NormalNode<T extends NodeData> extends Node<T> implements NodeAction<State> {

    @Override
    public final Map<String, Object> apply(State state) throws Exception {
        log.info("Node[{}] started, state[{}]", this.getClass().getSimpleName(), state);

        try {
            Instant start = Instant.now();
            Map<String, Object> result = process(state);
            Duration duration = Duration.between(start, Instant.now());
            log.info("Node[{}] finished in {}ms", this.getClass().getSimpleName(), duration.toMillis());
            return result;
        } catch (Exception e) {
            log.error("Node[{}] failed: {}", this.getClass().getSimpleName(), e.getMessage(), e);
            throw e;
        }
    }

    protected abstract Map<String, Object> process(State state) throws Exception;
}